package com.example.grpc.client;

import com.example.grpc.server.GreeterGrpc;
import com.example.grpc.server.HelloReply;
import com.example.grpc.server.HelloRequest;
import io.grpc.*;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;


public class HelloWorldCustomHeaderClient {
    private static final Logger logger = Logger.getLogger(HelloWorldCustomHeaderClient.class.getName());

    private Channel channel;
    private GreeterGrpc.GreeterBlockingStub blockingStub;

    public static void main(String[] args) throws Exception {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("service", "hello");
        headerMap.put("src-party-id", "9999");
        headerMap.put("src-role", "proxy");
        headerMap.put("dest-party-id", "300");
        headerMap.put("dest-role", "guest");

        ClientInterceptor interceptor = new com.example.grpc.client.HeaderClientInterceptor(headerMap);
        HelloWorldCustomHeaderClient client = new HelloWorldCustomHeaderClient("127.0.0.1", 6688, interceptor);

        String user = "Jerry";
        client.greet(user);

    }

    /**
     * Construct client connecting to HelloWorld server at {@code host:port}.
     */
    public HelloWorldCustomHeaderClient(String host, int port, ClientInterceptor interceptor) {
        ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port).usePlaintext();
        channel = channelBuilder.build();
        channel = ClientInterceptors.intercept(channel, interceptor);
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }


    /**
     * Say hello to server.
     */
    public void greet(String name) {
        logger.info("Will try to greet " + name + " ...");
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return;
        }
        logger.info("Greeting: " + response.getMessage());
    }

}
